import {defineStore} from "pinia";
import {IAesKey} from "@/iwb/IUser";
import {AesUtils} from "@/utils/AesUtils";
import {TimeUtils} from "@/utils/TimeUtils";
import {syncAesKey} from "@/api/user";

export const useEncryptStore = defineStore('encryptStore', {
    state: () => ({
        aesKey: {} as IAesKey
    }),
    actions: {
        async getAesKey() {
            let aesKey = this.aesKey;
            if (!aesKey.encryptKey || TimeUtils.isPastTime((aesKey.expireTime + aesKey.createTime) * 1000)) {
                this.aesKey = await AesUtils.createAesKey();
            }
            return this.aesKey;
        },
        syncAesKey(aesKey: IAesKey) {
            return new Promise((resolve, reject) => {
                syncAesKey(aesKey).then((res)=>{
                    resolve(res);
                }).catch(erro =>{
                    reject(erro);
                })
            })
        }
    }
})